<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="名字" width="120">
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="100" sortable>
			</el-table-column>
			<el-table-column prop="headImage" label="头像" width="100" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" min-width="100" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="部门" min-width="100" sortable>
			</el-table-column>
			<el-table-column label="操作" width="300">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="primary" size="small" @click="handlesetRole(scope.$index, scope.row)">设置角色</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
					layout="prev, pager, next"
					@current-change="handleCurrentChange"
					:page-size="query.pageSize"
					:total="pageInfo.total"
					:current-page="query.currentPage"
					style="float:right;">
			</el-pagination>
		</el-col>
		<el-dialog title="设置角色" :visible.sync="saveRoleVisible" :close-on-click-modal="false">
			<template scope="scope">
				<div>
				<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
				<div style="margin: 15px 0;"></div>
				<el-checkbox-group v-model="checkedroles" @change="handleCheckedrolesChange">
					<el-checkbox v-for="role in rolefrom.roles" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
				</el-checkbox-group>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveRoleVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveRole()" :loading="addLoading">提交</el-button>
			</div>
				</div>
			</template>
		</el-dialog>

		<!--
		新增/修改界面
		v-model="saveFormVisible"  这个它也是用来展示弹框的,但是现在已经过时了
		要换成  :visible.sync=
		:rules= 绑定校验规则
		 prop="name" 取校验规则中的某一个,
		-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="名字" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码">
					<el-input v-model="saveForm.password" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱">
					<el-input v-model="saveForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="头像">
					<el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门">
					<el-cascader v-model="saveForm.department"
								 :options="deptTree"
								 :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
								 clearable></el-cascader>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input v-model="saveForm.age" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	const rolesOption=[];
	export default {
		data() {
			return {
				filters: {
					name: ''
				},
				Employees: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				saveRoleVisible:false,
				saveFormVisible: false,//新增界面是否显示
				addLoading: false,
				saveFormRules: {
					username: [
						{ required: true, message: '请输入名字', trigger: 'blur' }
					]
				},
				//新增/修改-界面数据
				saveForm: {
					id:null,
					username: '',
					password:null,
					email:"",
					headImage:null,
					department:{
						id:null,
						name:""
					}
				},
				query:{
					currentPage:1,  // 当前页
					pageSize:10, // 每页显示条数
					keyword:""  // 关键字-查询条件
				},
				pageInfo:{
					total:0,  // 总条数
					rows:[] // 当前页数据
				},
				deptTree:[],
				checkAll: false,
				checkedroles: [],
				rolefrom:{
					roles:rolesOption ,
					employeeId:null
				},

				isIndeterminate: true

			}
		},
		methods: {

			handlesetRole(index,row){
				this.rolefrom.employeeId=row.id;
				console.log(row.id)
				this.handlerole();
				console.log(11111111111)

			},
			saveRole(){
				console.log(this.rolefrom);
					this.addLoading = true;
					this.$http.put("/employee/role",this.rolefrom)
					.then(result=>{
						this.addLoading = false;
						 result=result.data;
						if (result.success){
							this.$message({message: "保存成功!",type: 'success'});
						}else {
							this.$message({message: "网络异常,请检查网络!",type: 'error'});
						}
					}).catch(result=>{
						this.$message({message: "网络异常2221,请检查网络!",type: 'error'});
					})
				this.saveRoleVisible = false
				},
			handleCheckAllChange(val) {
				this.checkedroles = val ? rolesOption : [];
				this.isIndeterminate = false;
			},
			handleCheckedrolesChange(value) {
				let checkedCount = value.length;
				this.checkAll = checkedCount === this.rolefrom.roles.length;
				this.isIndeterminate = checkedCount > 0 && checkedCount < this.rolefrom.roles.length;
			},
			handlerole(index,row){
				this.saveRoleVisible=true;
				this.isIndeterminate = false;
				this.$http.get("/role")
				.then(result=>{
					let res=result.data;
					console.log(res.data)
					if (res.success){
						this.rolefrom.roles=res.data;
						console.log(this.rolefrom.roles)
					}else {
						this.$message({message: "网络异常,请检查网络!",type: 'error'});
					}
				}).catch(result=>{
					this.$message({message: "网络异常,请检查网络!",type: 'error'});
				})

			},
			search(){
				// 将当前页设置为1
				this.query.currentPage = 1;
				this.getEmployees();
			},
			handleCurrentChange(val) {  // 当 当前页的值被改变时触发
				// 将val(当前页)赋值给query.currentPage
				this.query.currentPage = val;
				// 调用查询方法,重新查询
				this.getEmployees();
			},
			//获取员工列表
			getEmployees() {
				console.log(this.query)
				this.$http.post("/employee",this.query)
						.then(result => { // 后端操作成功,进入then()
							console.log(result);
							result = result.data; // {success:true,message:"",dataObj:{}}
							if(result.success){ // true 后端返回了数据
								this.pageInfo = result.data;
							}else{ // false 说明后端处理失败
								this.$message({message: result.message,type: 'error'});
							}
						})
						.catch(result => {  // 如果报错 就会进入catch()
							this.$message({message: "网络异常,请检查网络!",type: 'error'});
						})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除这个数据吗?', '提示', {
					type: 'warning'
				}).then(() => {
					// 1 获取当前要删除数据的ID
					let id = row.id;
					// 2 调后端的删除接口
					this.$http.delete("/employee/"+id)
							.then(result => {
								result = result.data; // {success:true,message:""}
								if(result.success){
									// 提示"删除成功"
									this.$message({message: "删除成功!",type: 'success'});
									// 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
									this.query.currentPage = 1;
									// 调用查询方法
									this.getEmployees();
									// this.search();
								}else{
									this.$message({message: result.message,type: 'error'});
								}
							})
							.catch(result => {
								this.$message({message: "网络异常,请检查网络!",type: 'error'});
							})
				}).catch(() => {
					this.$message({message: '已取消删除!',type: 'info'});
				});
			},

			getdeptTree:function(){
				this.$http.get("/employee/tree")
				.then(result=>{
					result=result.data
					this.deptTree=result.data
				}).catch(result=>{
					this.$message({message: "网络异常,请检查网络!",type: 'error'});
				})

			},
			getemployees: function(){
				this.$http.get("/employee")
				.then(result=>{
					result=result.data
					if (result.success){
						this.employees=result.data
					}else {
						this.$message({message: "网络异常,请检查网络!",type: 'error'});
					}
				}).catch(result=>{
					this.$message({message: "网络异常,请检查网络!",type: 'error'});
				})
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				// 展示弹框
				this.saveFormVisible = true;
				// 将当前行的对象赋值给this.saveForm对象
				this.saveForm = Object.assign({}, row);
				console.log(this.saveForm);
				// 特殊处理manager parent
				// 如果manager parent没有值,为null的话,就给它们赋一个初识对象
				let temp=[];
				if(!this.saveForm.department){
					this.saveForm.department = {
						id:null,
						name: ""
					}
				}
				this.saveForm.department=row.department.id
				console.log(row.department.id)
				this.getdeptTree()
			},
			//显示新增界面
			handleAdd: function () {
				// 显示弹框
				this.saveFormVisible = true;
				// 初始化弹框的值,为了防止将上次的内容带到了下一次
				this.saveForm = {
					id:null,
					username: '',
					password:null,
					email:"",
					headImage:null,
					department:{
						id:null,
						name:""
					}
				};
				this.getdeptTree()
			},
			//编辑
			editSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.saveForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['saveForm'].resetFields();
								this.saveFormVisible = false;
								this.getEmployees();
							});
						});
					}
				});
			},
			//新增/修改的保存
			save: function () {
				// this.$refs.saveForm.validate((valid) => { 校验表单是否满足校验规则 valid=true 满足校验规则
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true; // 加载框
							console.log(this.saveForm)
							let param=this.saveForm
							if(param.department){
								param.department = {"id":param.department[param.department.length-1]}
							}
							// 调用后端接口-axios
							this.$http.put("/employee",param)
									.then(result => {
										// 获取后端返回的结果
										result = result.data; // {success:true,message:""}
										if(result.success){
											this.$message({message: "保存成功!",type: 'success'});
											// 关闭弹框
											this.saveFormVisible = false;

											// 关闭加载框
											this.addLoading = false;

											// 重新查询数据-(从当前页查询还是回到第一页,看需求)
											this.query.currentPage = 1;
											this.getEmployees();
										}else{
											this.$message({message: result.message,type: 'error'});
										}
									})
									.catch(result => {
										this.$message({message: "网络异常,请检查网络!",type: 'error'});
									})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				// 1 获取选中的要删除行的ID
				var ids = this.sels.map(item => item.id);
				console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					// 2 调后端的删除接口
					this.$http.patch("/employee",ids)
							.then(result => {
								result = result.data; // {success:true,message:""}
								if(result.success){
									// 提示"删除成功"
									this.$message({message: "删除成功!",type: 'success'});
									// 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
									this.query.currentPage = 1;
									// 调用查询方法
									this.getEmployees();
									// this.search();
								}else{
									this.$message({message: result.message,type: 'error'});
								}
							})
							.catch(result => {
								this.$message({message: "网络异常,请检查网络!",type: 'error'});
							})
				}).catch(() => {
					this.$message({message: '已取消删除!',type: 'info'});
				});
			}
		},
		mounted() {
			// 挂载完毕,就要去后端查询分页数据并展示
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>